const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

// 平台配置
const platforms = {
  windows: {
    target: 'nsis',
    arch: ['x64'],
    artifactName: '${productName}-${version}-win-${arch}.${ext}'
  },
  mac: {
    target: 'dmg',
    arch: ['x64', 'arm64'],
    artifactName: '${productName}-${version}-mac-${arch}.${ext}'
  },
  linux: {
    target: 'AppImage',
    arch: ['x64'],
    artifactName: '${productName}-${version}-linux-${arch}.${ext}'
  }
};

function log(message) {
  console.log(`[BUILD] ${new Date().toISOString()} - ${message}`);
}

function runCommand(command) {
  log(`执行命令: ${command}`);
  try {
    execSync(command, { stdio: 'inherit' });
  } catch (error) {
    log(`命令执行失败: ${error.message}`);
    throw error;
  }
}

function buildForPlatform(platform, config) {
  log(`开始构建 ${platform} 平台`);
  
  // 使用正确的平台参数格式
  const platformFlag = platform === 'windows' ? '--win' : platform === 'mac' ? '--mac' : '--linux';
  const archFlags = config.arch.map(arch => `--${arch}`).join(' ');
  const command = `npx electron-builder --publish=never ${platformFlag} ${archFlags} --config.artifactName="${config.artifactName}"`;
  
  runCommand(command);
  log(`${platform} 平台构建完成`);
}

async function buildAll() {
  try {
    // 确保输出目录存在
    const distDir = path.join(__dirname, 'dist');
    if (!fs.existsSync(distDir)) {
      fs.mkdirSync(distDir, { recursive: true });
    }

    log('开始构建项目...');
    runCommand('npm run build');
    
    log('开始跨平台打包...');
    
    // 构建所有平台
    for (const [platform, config] of Object.entries(platforms)) {
      try {
        await buildForPlatform(platform, config);
      } catch (error) {
        log(`${platform} 构建失败: ${error.message}`);
        // 继续构建其他平台
        continue;
      }
    }
    
    log('所有平台构建完成！');
    log('输出文件位置: ./dist/');
    
  } catch (error) {
    log(`构建过程出错: ${error.message}`);
    process.exit(1);
  }
}

async function buildSinglePlatform(targetPlatform) {
  try {
    // 验证平台是否支持
    if (!platforms[targetPlatform]) {
      log(`错误: 不支持的平台 "${targetPlatform}"`);
      log(`支持的平台: ${Object.keys(platforms).join(', ')}`);
      process.exit(1);
    }

    // 确保输出目录存在
    const distDir = path.join(__dirname, 'dist');
    if (!fs.existsSync(distDir)) {
      fs.mkdirSync(distDir, { recursive: true });
    }

    log('开始构建项目...');
    runCommand('npm run build');
    
    log(`开始构建 ${targetPlatform} 平台...`);
    
    // 构建指定平台
    await buildForPlatform(targetPlatform, platforms[targetPlatform]);
    
    log(`${targetPlatform} 平台构建完成！`);
    log('输出文件位置: ./dist/');
    
  } catch (error) {
    log(`构建过程出错: ${error.message}`);
    process.exit(1);
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  const args = process.argv.slice(2);
  
  if (args.length === 0) {
    // 没有参数，构建所有平台
    buildAll();
  } else if (args.length === 1) {
    // 有一个参数，构建指定平台
    const targetPlatform = args[0];
    buildSinglePlatform(targetPlatform);
  } else {
    // 参数错误
    console.log('使用方法:');
    console.log('  node build-all-platforms.js                # 构建所有平台');
    console.log('  node build-all-platforms.js <platform>     # 构建指定平台');
    console.log('');
    console.log('支持的平台: windows, mac, linux');
    process.exit(1);
  }
}

module.exports = { buildAll, buildSinglePlatform, buildForPlatform, platforms };